package com.webdemo.servlet;

import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.webdemo.dao.Dao;


/*
 * 处理登录信息的SERVLET
 */
@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	/*
	 * 用以比较用户输入的用户名和密码是否与数据库已存储的数据
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//字符串用以保存从页面传回的用户名和密码
		String userName = request.getParameter("username");
		String passWord = request.getParameter("password");
		
		//设置中文字符集
		request.setCharacterEncoding("utf-8");
		
		try {
			if(Dao.verify(userName, passWord)){
				//验证用户登录成功后，判断是否勾选了保存用户信息的选项
				request.setCharacterEncoding("utf-8");
				//判断用户是否勾选了保存用户信息的选项
				String[] isUseCookies =request.getParameterValues("isUseCookie");
				if(isUseCookies !=null && isUseCookies.length > 0)
				{
					
					Cookie usernameCookie = new Cookie("username",userName);
					Cookie passwordCookie = new Cookie("password",passWord);
					
					//设置Cookie的最大生存期限为10天
					usernameCookie.setMaxAge(864000);
					passwordCookie.setMaxAge(864000);
					
					//保存Cookie对象
					response.addCookie(usernameCookie);
					response.addCookie(passwordCookie);
				}
				
				//成功登陆，转发到笔记本页面
				request.getRequestDispatcher("Note.jsp").forward(request, response);
				
			}
			else {
				//登录失败，转发到重新登录页面
				request.getRequestDispatcher("NewNoteLogin.jsp").forward(request, response);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}

}
